package com.loongtech.bi.action;

import com.google.common.primitives.Bytes;
import com.loongtech.bi.entity.system.EntityBiChannel;
import com.loongtech.bi.entity.system.EntityBiPlatform;
import com.loongtech.bi.entity.system.EntityBiServer;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.support.Log;
import com.loongtech.core.util.Time;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import java.io.OutputStream;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 网页查询基类
 * 
 * @author Marin
 * @date 2015年09月30日
 */
public abstract class BaseBiSearchAction extends TransferHelper {
	private static final long serialVersionUID = 1L;
	private final static byte[] CSV_HEAD = { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };

	// 默认开始时间是7天前，结束时间是今天
	protected Date dateStart = new Date(Time.getBeginningOfDay(Time.currentTime() - 7 * Time.DAY));
	protected Date dateEnd = new Date(Time.getBeginningOfDay(Time.currentTime() - Time.DAY));
	protected String queryPlatform = "0"; // 前端传过来的查询条件：平台
	protected String queryChannel = "0"; // 前端传过来的查询条件：渠道
	protected String queryServer = "0"; // 前端传过来的查询条件：区服

	protected Map<String, String> platformItmes; // 平台下拉列表
	protected Map<String, String> channelItmes; // 渠道下拉列表
	protected Map<String, String> serverItmes; // 区服下拉列表

	public abstract void search();

	// 拼接成csv文件格式的字符串，用于保存
	protected abstract String csvContent();

	protected abstract String csvFileName();

	/**
	 * 初始化服务器列表和渠道列表
	 */
	@PostConstruct
	public void initData() {
		// 初始化平台下拉列到
		platformItmes = new LinkedHashMap<>();
		platformItmes.put("全平台", "0");
		for (EntityBiPlatform p : BiPlatformManager.PLATFORM_LIST) {
			platformItmes.put(p.getName(), p.getId());
		}
		updateChannelItmes();
	}

	/**
	 * 更新渠道下拉列表为queryPlatform下的所有渠道
	 */
	public void updateChannelItmes() {
		if (!"0".equals(queryPlatform)) {
			channelItmes = new LinkedHashMap<>();
			channelItmes.put("全渠道", "0");
			serverItmes = new LinkedHashMap<>();
			serverItmes.put("全区服", "0");

			return;
		}

		List<EntityBiChannel> list = BiPlatformManager.getChannelIdsByPlatformId(queryPlatform);

		channelItmes = new LinkedHashMap<>();
		channelItmes.put("全渠道", "0");
		for (EntityBiChannel c : list) {
			channelItmes.put(c.getName(), c.getId());
		}

		updateServerItmes();
	}

	/**
	 * 更新区服下拉列表为channelIds下的所有区服
	 */
	public void updateServerItmes() {
		if (!"0".equals(queryChannel)) {
			platformItmes = new LinkedHashMap<>();
			platformItmes.put("全平台", "0");
			serverItmes = new LinkedHashMap<>();
			serverItmes.put("全区服", "0");

			return;
		}

		platformItmes = new LinkedHashMap<>();
		platformItmes.put("全平台", "0");
		for (EntityBiPlatform p : BiPlatformManager.PLATFORM_LIST) {
			platformItmes.put(p.getName(), p.getId());
		}

		// List<EntityBiServer> list =
		// BiPlatformManager.getServerIdsByPlatAndChannId(queryPlatform,
		// queryChannel);
		List<EntityBiServer> list = BiPlatformManager.SERVER_LIST; // TODO
																	// 正式情况下，应该是上句，现在的情况是，没有区服渠道关联，所以渠道和平台为0时，直接返回全区服

		serverItmes = new LinkedHashMap<>();
		serverItmes.put("全区服", "0");
		for (EntityBiServer s : list) {
			serverItmes.put(s.getName(), s.getId());
		}
	}

	public void selectedServer() {
		if (!"0".equals(queryServer)) {
			platformItmes = new LinkedHashMap<>();
			platformItmes.put("全平台", "0");
			channelItmes = new LinkedHashMap<>();
			channelItmes.put("全渠道", "0");

			return;
		}

		/*
		 * platformItmes = new LinkedHashMap<>(); platformItmes.put("全平台", "0");
		 * for (EntityBiPlatform p : BiPlatformManager.PLATFORM_LIST) {
		 * platformItmes.put(p.getName(), p.getId()); }
		 */
		initData();
	}

	/**
	 * 保存成csv文件
	 * 
	 * @date 2015年1月3日
	 */
	public void saveAsCsv() {
		FacesContext context = FacesContext.getCurrentInstance();
		try {
			HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
			String fileName = java.net.URLEncoder.encode(
					csvFileName() + Time.formatTime(Time.currentTime(), "_yyyy_MM_dd_HH_mm_ss") + ".csv", "UTF-8");
			response.reset();
			response.setContentType("application/x-msdownload;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
			response.setCharacterEncoding("UTF-8");

			OutputStream responseOutputStream = response.getOutputStream();
			responseOutputStream.write(Bytes.concat(CSV_HEAD, csvContent().getBytes("UTF-8")));
			responseOutputStream.flush();
			responseOutputStream.close();

			context.addMessage(null, new FacesMessage("导出数据文件成功", "导出数据文件成功,fileName=" + fileName));
			context.responseComplete();
		} catch (Exception e) {
			Log.bi.error("保存CSV文件异常，fileName={}，class={}", csvFileName(), this.getClass().getSimpleName(), e);
			context.addMessage(null, new FacesMessage("导出数据文件失败", "导出文件发生异常"));
			return;
		}
	}

	public Date getDateStart() {
		return dateStart;
	}

	public void setDateStart(Date dateStart) {
		this.dateStart = dateStart;
	}

	public Date getDateEnd() {
		return dateEnd;
	}

	public void setDateEnd(Date dateEnd) {
		this.dateEnd = dateEnd;
	}

	public String getQueryPlatform() {
		return queryPlatform;
	}

	public void setQueryPlatform(String queryPlatform) {
		this.queryPlatform = queryPlatform;
	}

	public String getQueryChannel() {
		return queryChannel;
	}

	public void setQueryChannel(String queryChannel) {
		this.queryChannel = queryChannel;
	}

	public String getQueryServer() {
		return queryServer;
	}

	public void setQueryServer(String queryServer) {
		this.queryServer = queryServer;
	}

	public Map<String, String> getPlatformItmes() {
		return platformItmes;
	}

	public void setPlatformItmes(Map<String, String> platformItmes) {
		this.platformItmes = platformItmes;
	}

	public Map<String, String> getChannelItmes() {
		return channelItmes;
	}

	public void setChannelItmes(Map<String, String> channelItmes) {
		this.channelItmes = channelItmes;
	}

	public Map<String, String> getServerItmes() {
		return serverItmes;
	}

	public void setServerItmes(Map<String, String> serverItmes) {
		this.serverItmes = serverItmes;
	}

}
